<script setup>

const router = useRouter()
const layout = "orange";
const urlHome = useUrl();
// const { setPeriodsDates } = periodDateStore();
// const { periods } = storeToRefs(periodDateStore());
useHead({
    title: 'HLS: Авторизация',
})
const error_message = useLoginErrorMessage();
error_message.value = '';
definePageMeta({
    layout: "flat",
})


// var os = require('os');
// os.userInfo().username
// const userName = ref('')
// userName.value = os.userInfo().username

// var path = require('path');
// var userName = process.env['USERPROFILE'].split(path.sep)[2];
// var loginId = path.join("domainName", userName);
// console.log(loginId);
// async function periodDatesInitialized() {
//     const response = await $fetch(`${urlHome.value}lab/period_date/`);
//     if (response.ok) {
//         setPeriodsDates(response.dates);
//     } else {

//     }
// }
// periodDatesInitialized()

const auth_data = router.currentRoute.value.query;
const { params } = useRoute();

const username = ref('');
username.value = auth_data.login;
const password = ref('');
password.value = auth_data.password;
const user = useCookie('user');
const mpp = useCookie('mpp');
const access_list = useCookie('access_list');
const fio_short = useCookie('fio_short');
const dolzh = useCookie('dolzh');


async function submit() {

    let formData = new FormData();
    if (username.value !== undefined) {
        formData.append('username', username.value.toLowerCase());
        formData.append('password', password.value);
    }
    const response = await $fetch(`${urlHome.value}auth/login_vue/`, {
        method: 'POST',
        body: formData,
    })
    if (response.ok) {
        user.value = response.username
        mpp.value = response.mpp
        access_list.value = response.access
        fio_short.value = response.fio_short
        dolzh.value = response.dolzh
        if (['Программист', 'Бухгалтер', 'Старший техник', 'Регистратор'].includes(dolzh.value)) {
            console.log("movement")
            navigateTo('/menu')
        }
        // if (dolzh.value === 'Программист') {
        //     navigateTo('/menu')
        // } else if (dolzh.value === 'Бухгалтер') {
        //     navigateTo('/menu_buh')
        // } else if (dolzh.value === 'Старший техник') {
        //     navigateTo('/menu_st')
        else {
            navigateTo('/lab/naryad_list')
        }
    } else if (!response.ok && response.status === 201) {
        error_message.value = response.message
    }
}

const colorMode = useColorMode()
const isDark = computed({
    get() {
        return colorMode.value === 'dark'
    },
    set() {
        colorMode.preference = colorMode.value === 'dark' ? 'light' : 'dark'
    }
})

</script>

<template>
    <div>
        <ClientOnly>
            <UButton :icon="isDark ? 'i-heroicons-moon-20-solid' : 'i-heroicons-sun-20-solid'" color="gray"
                variant="ghost" aria-label="Theme" @click="isDark = !isDark" />
            <template #fallback>
                <div class="w-8 h-8" />
            </template>
        </ClientOnly>
        <div class="flex min-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
            <div class="w-full max-w-md space-y-8">
                <div>
                    <img class="mx-auto w-auto" src="/img/logo.svg" alt="Логотип" />
                    <h1 class="mt-6 text-center text-3xl font-bold tracking-tight">Зуботехническая лаборатория
                    </h1>
                    <p class="mt-2 text-center text-sm"></p>
                    <h2 class="text-center" @click="navigateTo('http://192.168.100.19:9000/', { external: true })">
                        Перейти в
                        Гелиос</h2>
                </div>
                <input type="hidden" name="remember" value="true" />
                <div class="-space-y-px rounded-md shadow-sm">
                    <div>
                        <UInput v-model="username" id="username" name="username" autocomplete="true" type="text"
                            label="Логин" required
                            class="relative block w-full appearance-none rounded-none rounded-t-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"
                            placeholder="Пользователь" />
                    </div>
                    <div>
                        <UInput @keypress.enter="submit()" v-model="password" id="password" name="password"
                            type="password" label="Пароль" autocomplete="current-password" required
                            class="relative block w-full appearance-none rounded-none rounded-b-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-500 focus:z-10 focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 sm:text-sm"
                            placeholder="Пароль" />
                    </div>
                </div>

                <div>
                    <UButton @click="submit()" color="primary"
                        class="group relative flex w-full justify-center rounded-md border border-transparent  focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
                        type="button" label="Авторизоваться">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                        </span>
                        Авторизоваться
                    </UButton>
                </div>
                <div v-if="error_message.value != ''">
                    <div class="alert alert-error shadow-lg">
                        <div>
                            <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current flex-shrink-0 h-6 w-6"
                                fill="none" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <span>{{ error_message.value }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>